package cn.itsource;

import cn.itsource.bean.Student;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ExportDataUsingJxls {
    public static void main(String[] args) {
        // 模板文件路径
        String templateFile = "D:\\Java\\Javawork\\JavaWeb\\pethome\\src\\main\\resources\\test.xls";  // 在resources目录下

        // 导出文件路径
        String outputFile = "D:\\Java\\Javawork\\JavaWeb\\pethome\\src\\main\\resources\\output.xls";

        // 数据准备
        List<Student> dataList = generateData();

        try (FileInputStream fis = new FileInputStream(templateFile) {
        };
             FileOutputStream fos = new FileOutputStream(outputFile)) {

            // 使用JxlsHelper进行导出
            Context context = new Context();
            context.putVar("dataList", dataList);

            JxlsHelper.getInstance().processTemplateAtCell(fis, fos, context, "Sheet1!A1");

            System.out.println("数据导出成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static List<Student> generateData() {
        // 生成随机数据
        List<Student> dataList = new ArrayList<>();
        Random random = new Random();

        for (int i = 0; i < 10; i++) {
            Student student = new Student();
            student.setName("姓名" + (i+1));
            student.setAge( random.nextInt(30) + 20);  // 年龄范围在20-50岁之间
            student.setSchool("学校" + (i+1));
            dataList.add(student);
        }

        return dataList;
    }
}
